/*
 * Copyright (c) 2014 pkzd/1.0, 颜文泽(robin)
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     1 Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     2 Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include	<sig.h>
#include	<map.h>

void
signal(pid_t pgrp, uint sig)
{
	struct proc *p;

	if(!pgrp) 
		return;
	for(p = &proc[0]; p < &proc[NPROC]; p++)
		if(p->p_pgrp == pgrp)
			psignal(p, sig);
}

void
psignal(struct proc *p, uint sig)
{
	if(!sig || sig > NSIG)
		return;
	p->p_sig |= 1 << (sig - 1);
	if(p->p_stat == SWAIT)
		pready(p);	
	if(p == up)
		issig(p);
}

uint
issig(struct proc *p)
{
	uint n;
	struct proc *rp;

	while(p->p_sig){
		if(n = fsig(p)){
			if(p->p_signal[n - 1] == SIG_DFL)
				exit(n);
			if(n == SIGCHLD && p->p_signal[n - 1] == SIG_IGN){
				for(rp = &proc[0]; rp < &proc[NPROC]; rp++){
					if(p->p_pid == rp->p_ppid && rp->p_stat == SZOMB){
						freeproc(rp);
						rp->p_sig = 0;	
						rp->p_pid = 0;	
						rp->p_exit = 0;
						rp->p_ppid = 0;
						rp->p_pgrp = 0;
						rp->p_wchan = NULL;
						rp->p_stat = SFREE;
						mfree(kernmap, 1, (uint)rp->p_pgdir);
						mfree(kernmap, 1, (uint)rp->p_stack);
						p->p_time += rp->p_time;
						rp->p_time = 0;
					}
				}
			}
			p->p_sig &= ~(1 << (n - 1));
		}
	}
	return 0;
}

uint
fsig(struct proc *p)
{
	uint i, n;
		
	n = p->p_sig;
	for(i = 1; i <= NSIG; i++){
		if(n & 0x1)
			return i;	
		n >>= 1;
	}
	return 0;
}
